///
/// 多选框组件
/// 参照Element UI的Checkbox控件实现

import 'package:flutter/material.dart';
import '../../core/elegance_theme.dart';

/// 多选框大小类型枚举
enum ECheckboxSize {
  /// 小型多选框
  small,
  
  /// 普通大小多选框
  normal,
}

/// ECheckbox组件
class ECheckbox<T> extends StatefulWidget {
  /// 创建ECheckbox组件
  const ECheckbox({
    super.key,
    required this.value,
    required this.checked,
    this.onChanged,
    this.label,
    this.size = ECheckboxSize.normal,
    this.disabled = false,
    this.indeterminate = false,
    this.border = true,
    this.textStyle,
    this.name,
  });

  /// 当前多选框的值
  final T value;
  
  /// 是否被选中
  final bool checked;
  
  /// 选中状态变更回调
  final ValueChanged<T>? onChanged;
  
  /// 多选框旁边的文本标签
  final String? label;
  
  /// 多选框大小
  final ECheckboxSize size;
  
  /// 是否禁用
  final bool disabled;
  
  /// 是否处于不确定状态（用于全选）
  final bool indeterminate;
  
  /// 是否显示边框
  final bool border;
  
  /// 自定义文本样式
  final TextStyle? textStyle;
  
  /// 原生name属性
  final String? name;

  @override
  State<ECheckbox<T>> createState() => _ECheckboxState<T>();
}

class _ECheckboxState<T> extends State<ECheckbox<T>> {
  /// 是否处于悬浮状态
  bool _isHovered = false;
  
  /// 是否处于按下状态
  bool _isPressed = false;
  
  /// 处理点击事件
  void _handleTap() {
    if (!widget.disabled && widget.onChanged != null) {
      widget.onChanged!(widget.value);
    }
  }
  
  /// 获取多选框尺寸
  double _getCheckboxSize() {
    switch (widget.size) {
      case ECheckboxSize.small:
        return 14.0;
      case ECheckboxSize.normal:
      default:
        return 18.0;
    }
  }
  
  /// 获取边框宽度
  double _getBorderWidth() {
    return widget.disabled ? 1.0 : 1.5;
  }
  
  /// 获取文本字体大小
  double _getTextFontSize() {
    switch (widget.size) {
      case ECheckboxSize.small:
        return 12.0;
      case ECheckboxSize.normal:
      default:
        return 14.0;
    }
  }
  
  /// 获取多选框颜色
  Color _getCheckboxColor(EleganceThemeData theme) {
    if (widget.disabled) {
      return theme.textPlaceholderColor;
    }
    
    if (_isPressed) {
      return theme.primaryDark;
    }
    
    if (_isHovered) {
      return theme.primaryColor.withOpacity(0.8);
    }
    
    return theme.primaryColor;
  }
  
  /// 获取背景颜色
  Color _getBackgroundColor(EleganceThemeData theme) {
    if (widget.disabled) {
      return Colors.transparent;
    }
    
    return Colors.transparent;
  }
  
  /// 获取文本颜色
  Color _getTextColor(EleganceThemeData theme) {
    if (widget.disabled) {
      return theme.textPlaceholderColor;
    }
    
    return widget.textStyle?.color ?? theme.textPrimaryColor;
  }
  
  /// 获取对勾图标
  Widget _getCheckIcon(Color color) {
    final iconSize = _getCheckboxSize() * 0.6;
    
    if (widget.indeterminate) {
      // 不确定状态显示横线
      return Center(
        child: Container(
          width: iconSize * 0.8,
          height: 2.0,
          color: color,
        ),
      );
    }
    
    // 选中状态显示对勾
    return Icon(
      Icons.check,
      size: iconSize,
      color: color,
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = EleganceTheme.of(context);
    final size = _getCheckboxSize();
    final borderWidth = _getBorderWidth();
    final textFontSize = _getTextFontSize();
    final checkboxColor = _getCheckboxColor(theme);
    final backgroundColor = _getBackgroundColor(theme);
    final textColor = _getTextColor(theme);
    
    // 构建多选框核心部分
    final checkboxWidget = Container(
      width: size,
      height: size,
      decoration: BoxDecoration(
        shape: BoxShape.rectangle,
        borderRadius: BorderRadius.circular(4.0),
        border: Border.all(
          color: widget.disabled 
            ? theme.borderColor 
            : (widget.checked || widget.indeterminate) 
              ? checkboxColor 
              : (_isHovered ? theme.primaryColor.withOpacity(0.6) : theme.borderColor),
          width: borderWidth,
        ),
        color: widget.disabled 
          ? Colors.transparent 
          : (widget.checked || widget.indeterminate) 
            ? checkboxColor 
            : backgroundColor,
      ),
      child: (widget.checked || widget.indeterminate) && !widget.disabled
          ? _getCheckIcon(Colors.white)
          : null,
    );
    
    // 构建完整的多选框组件（包含可选的文本标签）
    Widget child;
    if (widget.label != null) {
      child = Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          checkboxWidget,
          const SizedBox(width: 8.0),
          Text(
            widget.label!, 
            style: TextStyle(
              fontSize: widget.textStyle?.fontSize ?? textFontSize,
              color: textColor,
              fontWeight: widget.textStyle?.fontWeight ?? FontWeight.normal,
            ),
          ),
        ],
      );
    } else {
      child = checkboxWidget;
    }
    
    // 添加事件处理和状态
    return MouseRegion(
      onEnter: (_) {
        if (!widget.disabled) {
          setState(() {
            _isHovered = true;
          });
        }
      },
      onExit: (_) {
        if (!widget.disabled) {
          setState(() {
            _isHovered = false;
            _isPressed = false;
          });
        }
      },
      cursor: widget.disabled ? MouseCursor.defer : SystemMouseCursors.click,
      child: GestureDetector(
        onTapDown: (_) {
          if (!widget.disabled) {
            setState(() {
              _isPressed = true;
            });
          }
        },
        onTapUp: (_) {
          if (!widget.disabled) {
            setState(() {
              _isPressed = false;
            });
          }
        },
        onTapCancel: () {
          if (!widget.disabled) {
            setState(() {
              _isPressed = false;
            });
          }
        },
        onTap: _handleTap,
        child: child,
      ),
    );
  }
}

/// ECheckboxGroup组件 - 用于管理一组多选框
class ECheckboxGroup<T> extends StatefulWidget {
  /// 创建ECheckboxGroup组件
  const ECheckboxGroup({
    super.key,
    this.value = const [],
    this.onChanged,
    this.children,
    this.disabled = false,
    this.min = 0,
    this.max = 999999,
    this.size,
    this.textColor,
    this.fill,
    this.direction = Axis.vertical,
  });
  
  /// 当前选中的值列表
  final List<T> value;
  
  /// 值变更回调
  final ValueChanged<List<T>>? onChanged;
  
  /// 子组件（通常是多个ECheckbox）
  final List<Widget>? children;
  
  /// 是否禁用整个多选组
  final bool disabled;
  
  /// 可被勾选的最小数量
  final int min;
  
  /// 可被勾选的最大数量
  final int max;
  
  /// 多选框大小
  final ECheckboxSize? size;
  
  /// 按钮形式的多选框激活时的文本颜色
  final Color? textColor;
  
  /// 按钮形式的多选框激活时的填充色和边框色
  final Color? fill;
  
  /// 子组件排列方向
  final Axis direction;
  
  @override
  State<ECheckboxGroup<T>> createState() => _ECheckboxGroupState<T>();
}

class _ECheckboxGroupState<T> extends State<ECheckboxGroup<T>> {
  /// 处理子组件的值变更
  void _handleCheckboxChanged(T value) {
    final newValue = List<T>.from(widget.value);
    
    if (newValue.contains(value)) {
      // 如果当前值已存在，且移除后数量不小于最小值，则移除
      if (newValue.length > widget.min) {
        newValue.remove(value);
      }
    } else {
      // 如果当前值不存在，且添加后数量不大于最大值，则添加
      if (newValue.length < widget.max) {
        newValue.add(value);
      }
    }
    
    if (widget.onChanged != null) {
      widget.onChanged!(newValue);
    }
  }
  
  @override
  Widget build(BuildContext context) {
    // 处理子组件，将多选框的值和事件处理绑定到多选组
    Widget child;
    if (widget.direction == Axis.vertical) {
      child = Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: widget.children ?? [],
      );
    } else {
      child = Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: widget.children ?? [],
      );
    }
    
    // 提供CheckboxGroup的InheritedWidget给子组件
    return _ECheckboxGroupProvider<T>(
      value: widget.value,
      onChanged: _handleCheckboxChanged,
      disabled: widget.disabled,
      size: widget.size,
      textColor: widget.textColor,
      fill: widget.fill,
      child: child,
    );
  }
}

/// ECheckboxGroup的InheritedWidget实现，用于向下传递值和回调
class _ECheckboxGroupProvider<T> extends InheritedWidget {
  const _ECheckboxGroupProvider({
    required super.child,
    required this.value,
    required this.onChanged,
    required this.disabled,
    this.size,
    this.textColor,
    this.fill,
  });
  
  final List<T> value;
  final void Function(T) onChanged;
  final bool disabled;
  final ECheckboxSize? size;
  final Color? textColor;
  final Color? fill;
  
  @override
  bool updateShouldNotify(_ECheckboxGroupProvider<T> oldWidget) {
    return value != oldWidget.value || 
           onChanged != oldWidget.onChanged || 
           disabled != oldWidget.disabled ||
           size != oldWidget.size ||
           textColor != oldWidget.textColor ||
           fill != oldWidget.fill;
  }
  
  // 静态方法，用于子组件获取CheckboxGroup的值和回调
  static _ECheckboxGroupProvider<T>? of<T>(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<_ECheckboxGroupProvider<T>>();
  }
}

/// ECheckboxButton组件 - 按钮样式的多选框
class ECheckboxButton<T> extends StatefulWidget {
  /// 创建ECheckboxButton组件
  const ECheckboxButton({
    super.key,
    required this.value,
    this.checked = false,
    this.onChanged,
    this.label = '',
    this.disabled = false,
    this.name,
    this.textColor,
    this.fill,
  });
  
  /// 当前多选框按钮的值
  final T value;
  
  /// 是否被选中
  final bool checked;
  
  /// 选中状态变更回调
  final ValueChanged<T>? onChanged;
  
  /// 按钮文本
  final String label;
  
  /// 是否禁用
  final bool disabled;
  
  /// 原生name属性
  final String? name;
  
  /// 激活时的文本颜色
  final Color? textColor;
  
  /// 激活时的填充色和边框色
  final Color? fill;
  
  @override
  State<ECheckboxButton<T>> createState() => _ECheckboxButtonState<T>();
}

class _ECheckboxButtonState<T> extends State<ECheckboxButton<T>> {
  /// 是否处于悬浮状态
  bool _isHovered = false;
  
  /// 获取父级CheckboxGroup的属性
  _ECheckboxGroupProvider<T>? _getGroup() {
    return _ECheckboxGroupProvider.of<T>(context);
  }
  
  /// 判断是否选中
  bool _isChecked() {
    final group = _getGroup();
    if (group != null) {
      return group.value.contains(widget.value);
    }
    return widget.checked;
  }
  
  /// 判断是否禁用
  bool _isDisabled() {
    final group = _getGroup();
    if (group != null) {
      return group.disabled || widget.disabled;
    }
    return widget.disabled;
  }
  
  /// 处理点击事件
  void _handleTap() {
    if (_isDisabled()) {
      return;
    }
    
    final group = _getGroup();
    if (group != null) {
      group.onChanged(widget.value);
    } else if (widget.onChanged != null) {
      widget.onChanged!(widget.value);
    }
  }
  
  /// 获取文本颜色
  Color _getTextColor(EleganceThemeData theme) {
    if (_isDisabled()) {
      return theme.textPlaceholderColor;
    }
    
    final isChecked = _isChecked();
    if (isChecked) {
      final group = _getGroup();
      return group?.textColor ?? widget.textColor ?? Colors.white;
    }
    
    return theme.textPrimaryColor;
  }
  
  /// 获取背景颜色
  Color _getBackgroundColor(EleganceThemeData theme) {
    if (_isDisabled()) {
      return theme.surfaceColor;
    }
    
    final isChecked = _isChecked();
    if (isChecked) {
      final group = _getGroup();
      return group?.fill ?? widget.fill ?? theme.primaryColor;
    }
    
    return _isHovered ? theme.primaryLight : theme.surfaceColor;
  }
  
  /// 获取边框颜色
  Color _getBorderColor(EleganceThemeData theme) {
    if (_isDisabled()) {
      return theme.borderColor;
    }
    
    final isChecked = _isChecked();
    if (isChecked) {
      final group = _getGroup();
      return group?.fill ?? widget.fill ?? theme.primaryColor;
    }
    
    return _isHovered ? theme.primaryColor : theme.borderColor;
  }
  
  @override
  Widget build(BuildContext context) {
    final theme = EleganceTheme.of(context);
    final isChecked = _isChecked();
    final isDisabled = _isDisabled();
    final textColor = _getTextColor(theme);
    final backgroundColor = _getBackgroundColor(theme);
    final borderColor = _getBorderColor(theme);
    
    final buttonWidget = Container(
      padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 6.0),
      decoration: BoxDecoration(
        color: backgroundColor,
        border: Border.all(
          color: borderColor,
          width: 1.0,
        ),
        borderRadius: BorderRadius.circular(theme.borderRadius),
      ),
      child: Text(
        widget.label,
        style: TextStyle(
          color: textColor,
          fontSize: 14.0,
          fontWeight: FontWeight.normal,
        ),
      ),
    );
    
    return MouseRegion(
      onEnter: (_) {
        if (!isDisabled) {
          setState(() {
            _isHovered = true;
          });
        }
      },
      onExit: (_) {
        if (!isDisabled) {
          setState(() {
            _isHovered = false;
          });
        }
      },
      cursor: isDisabled ? MouseCursor.defer : SystemMouseCursors.click,
      child: GestureDetector(
        onTap: _handleTap,
        child: buttonWidget,
      ),
    );
  }
}